﻿using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 资源生成和回收池
/// 用来解决类似发射无数子弹的需求
/// </summary>
public class ObjectPool
{
    Queue<GameObject> objInPool;//在池中的物体
    GameObject obj;
    Transform parent;
    public GameObject gameobjcet;
    /// <summary>
    /// 拥有对象资源的数量
    /// </summary>
    public int InCount
    {
        get { return objInPool.Count; }
    }

    /// <summary>
    /// 从资源池中获取闲置的物体并返回
    /// </summary>
    /// <param name="gameObject">放入对象池中的物体类型</param>
    /// <param name="ParentName">根节点名</param>
    /// <param name="Count">数量</param>
    public ObjectPool(GameObject gameObject, string ParentName = "defultPool", int Count = 50)
    {
        obj = gameObject;
        gameobjcet = new GameObject(ParentName);

        parent = gameobjcet.transform;
        parent.name = ParentName;
        if (gameObject!=null)
        {
            objInPool = new Queue<GameObject>();
            for (int i = 1; i < Count; i++)
            {
                GameObject temp = GameObject.Instantiate(gameObject, parent);
                temp.SetActive(false);//默认隐藏掉
                objInPool.Enqueue(temp);
            }
        }
        else
        {
            Debug.Log("gameobject为空");
        }
    }

    /// <summary>
    /// 从资源池加载物体
    /// </summary>
    /// <returns></returns>
    public GameObject GetObjInPool()
    {
        if (InCount > 0)//这是对象池中物体数量够的情况下 从栈中取出来直接使用即可
        {
            GameObject temp = objInPool.Dequeue();
            temp.SetActive(true);
            return temp;
        }
        else//当对象池中物体数量不够时   我们需要动态创建物体
        {
            GameObject temp = GameObject.Instantiate(obj, parent);
            objInPool.Enqueue(temp);
            return objInPool.Dequeue();
        }
    }
    
    /// <summary>
    /// 回收物体     将用完的物体放回队列中等待下一次取出
    /// </summary>
    /// <param name="gameObject"></param>
    public void DestoryObjInOutPool(GameObject gameObject)
    {
        gameObject.transform.localPosition = Vector3.zero;
        gameObject.transform.localRotation =Quaternion.Euler(Vector3.zero);
        gameObject.SetActive(false);
        objInPool.Enqueue(gameObject);
    }

    /// <summary>
    /// 删除所有池中闲置物体  这里不会删除正在使用的物体
    /// </summary>
    public void DestoryAllGameObject()
    {
        foreach (var item in objInPool)
        {
            GameObject.Destroy(item.gameObject);
        }
        objInPool.Clear();
    }
}
